package com.stedu.mall.userservice.controller;

import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Collect;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CollectService;
import com.stedu.mall.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/collect")
public class CollectController {
   @Autowired
    private CollectService collectService;
    //添加
    @PostMapping("/{goodsId}")
    public RespBean insert(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) throws SteduException {
        Map<String,Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId =(Integer)map.get("id");
        Collect collect = new Collect();
        collect.setGoodsId(goodsId);
        collect.setUserId(userId);
        collectService.insert(collect);
        return  RespBean.ok("添加成功");
    }

    //删除---取消收藏
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token ) throws SteduException {
        Map<String,Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId =(Integer)map.get("id");
        collectService.delete(id,userId);
        return RespBean.ok("取消收藏成功");

    }

    //根据商品id用户id查询收藏
@GetMapping("/{goodsId}")
    public  RespBean selectByGoodsIdAndUserId(@PathVariable("goodsId") Integer goodsId,@RequestHeader("token") String token) {
    Map<String, Object> map = JwtUtil.parseJwtToMap(token);
    Integer userId = (Integer) map.get("id");
    Collect collect = collectService.selectByGoodsIdAndUserId(goodsId, userId);
    return RespBean.ok("查询成功",collect);
}

    //根据id查询收藏信息
        @GetMapping
    public RespBean selectByPage(Integer pageNum, Integer pageSize,@RequestHeader("token") String token ) throws SteduException {
        pageNum = pageNum==null ? 1:pageNum;
        pageSize = pageSize==null ? 5:pageSize;
        Map<String,Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId =(Integer)map.get("id");
        PageInfo<Collect> pageInfo =collectService.selectBypage(userId, pageNum, pageSize);
        return RespBean.ok("查询成功",pageInfo);
    }

}
